//
//  BzVC.swift
//  Auscultation
//
//  Created by 来 on 2020/12/13.
//

import UIKit

class BzModel: NSObject {
    var operator_: String = ""
    var operatorName: String = ""
    var coordinate: [[String: Any]]!
    var markOption: [String] = []
    var diagnosis: [String] = []
    var remark: String = ""
    var markId: String = ""
    var isDifficult: Int = 0
    var isSame: Int = 0
    var rating: Int = 0
    var ratingRemark: String = ""
    var backgroundColor: UIColor = UIColor.init(lgf_HexString: "F0F0F0")
}

class BzVC: BaseVC {
    
    // 页面类型 1 标注 2 审核 3 仲裁 4 审核对比医生 5 仲裁对比医生
    var stype: Int = 0
    // 标注页面类型 1 标注完成 2 标注开始 3 审核完成 4 审核开始 5 已仲裁 6 未仲裁
    var type: Int = 0
    
    // 数据
    var id: String = ""
    var labelId: String = ""
    var auditId: String = ""
    var arbitrationId: String = ""
    var auditStatus: Int = 0
    var labelStatus: Int = 0
    var isArbitration: Int = 0 // 仲裁：0：无需；1：正在；2：完成
    var diagnose: String = "" // 心超诊断
    var descn: String = "" // 临床诊断
    var isDeleted: Int = 1 // 是否删除,0作废,1有效
    var reportPath: String = ""
    var sampleDetail: [String: Any]?
    
    // 诊区
    var areaFirst: [String: Any]!
    var areaSecond: [String: Any]!
    var areaThird: [String: Any]!
    var areaFourth: [String: Any]!
    var areaFifth: [String: Any]!
    
    // 标注内容字典
    var bzModel: BzModel!
    var bzModels: [BzModel] = []
    var selectCoordinates: [[[String: Any]]] = []
    var bznrArr: [[String: Any]] = []
    var zsjgArr: [[String: Any]] = []
    var spNums: [Double] = []
    
    var ph_view_i_top: UIView!
    var ph_view: UIScrollView!
    var ph_view_i: UIImageView!
    var ph_view_i_w: CGFloat = 0
    var ph_l: bzxV!
    var ph_r: bzxV!
    var sp_view: UIView!
    var sp_l: bzxV!
    
    // 顶部栏
    var wc: UILabel!
    var zf: UILabel!
    var qhsp: UILabel!
    var qhsp2: UILabel!
    var tzms: UILabel!
    var ckbg: UILabel!
    var ysbz: UILabel!
    
    var ys: UILabel!
    var add_dbys: UILabel!
    var dbys_b: UIScrollView!
    var s_dbys_i: [Int] = []
    var wc_b: UIView!
    
    var ysqhV: YsqhV!
    
    var sd_l: UILabel!
    var sy_l: UILabel!
    var xz_l: UILabel!
    var xf: Int = 5
    var yz: UIView!
    var yz_l: UILabel!
    
    var pf: UIView!
    var kxbz: UIView!
    var zdbz: UIView!
    
    var kxbzv: KxBzV!
    var kxbz_l: UILabel!
    
    // 播放
    var play_button: UIButton!
    // 时间
    var play_time: UILabel!
    var play_time_all: UILabel!
    // 进度
    var play_line: UISlider!
    
    var wavPath: String!
    var wavDataPath: String!
    var wavBdPath: String!
    
    var player: LGFAudioPlayer!
    
    var isPlay: Bool = false
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        isHorizontalScreen = true
        isScreenPanPopEnabled = false
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        paused()
    }
    
    deinit {
        stop()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        player = LGFAudioPlayer()
        player.delegate = self
        getData()
    }
    
    // 标注页状态 1 标注完成 2 标注开始 3 审核完成 4 审核开始
    func autoType() {
        if type == 1 {
            wc_b.isHidden = false
            pf.isHidden = true
            ys.isHidden = true
            dbys_b.isHidden = true
            add_dbys.isHidden = true
            qhsp2.isHidden = true
            kxbz.isHidden = true
            zdbz.isHidden = false
            ysbz.isHidden = true
            ysbz.snp.updateConstraints { (make) in
                make.right.equalTo(ckbg.snp.left).offset(0)
                make.width.equalTo(0)
            }
            zf.isHidden = true
            zf.snp.updateConstraints { (make) in
                make.right.equalTo(wc.snp.left).offset(0)
                make.width.equalTo(0)
            }
        } else if type == 2 {
            wc_b.isHidden = false
            pf.isHidden = true
            ys.isHidden = true
            dbys_b.isHidden = true
            add_dbys.isHidden = true
            qhsp2.isHidden = true
            kxbz.isHidden = false
            zdbz.isHidden = false
            ysbz.isHidden = true
            ysbz.snp.updateConstraints { (make) in
                make.right.equalTo(ckbg.snp.left).offset(0)
                make.width.equalTo(0)
            }
            zf.isHidden = true
            zf.snp.updateConstraints { (make) in
                make.right.equalTo(wc.snp.left).offset(0)
                make.width.equalTo(0)
            }
        } else if type == 3 {
            wc_b.isHidden = false
            pf.isHidden = true
            dbys_b.isHidden = true
            add_dbys.isHidden = true
            qhsp2.isHidden = true
            zdbz.isHidden = false
            zf.isHidden = true
            kxbz.isHidden = true
            zf.snp.updateConstraints { (make) in
                make.right.equalTo(wc.snp.left).offset(0)
                make.width.equalTo(0)
            }
        } else if type == 4 {
            wc_b.isHidden = false
            pf.isHidden = true
            dbys_b.isHidden = true
            add_dbys.isHidden = true
            qhsp2.isHidden = true
            zdbz.isHidden = false
            zf.isHidden = true
            kxbz.isHidden = false
            zf.snp.updateConstraints { (make) in
                make.right.equalTo(wc.snp.left).offset(0)
                make.width.equalTo(0)
            }
        } else if type == 10 {// 医生对比
            wc_b.isHidden = true
            pf.isHidden = false
            ys.isHidden = false
            dbys_b.isHidden = false
            add_dbys.isHidden = false
            qhsp2.isHidden = false
            kxbz.isHidden = true
            zdbz.isHidden = false
            zdbz.snp.updateConstraints { (make) in
                make.right.equalTo(play_time.snp.right).offset(-80)
            }
            ysbz.isHidden = true
            ysbz.snp.updateConstraints { (make) in
                make.right.equalTo(ckbg.snp.left).offset(0)
                make.width.equalTo(0)
            }
            zf.isHidden = true
            zf.snp.updateConstraints { (make) in
                make.right.equalTo(wc.snp.left).offset(0)
                make.width.equalTo(0)
            }
        } else if type == 5 {
            wc_b.isHidden = false
            pf.isHidden = true
            dbys_b.isHidden = true
            add_dbys.isHidden = true
            qhsp2.isHidden = true
            zdbz.isHidden = false
            zf.isHidden = true
            kxbz.isHidden = true
            zf.snp.updateConstraints { (make) in
                make.right.equalTo(wc.snp.left).offset(0)
                make.width.equalTo(0)
            }
        } else if type == 6 {
            wc_b.isHidden = false
            pf.isHidden = true
            dbys_b.isHidden = true
            add_dbys.isHidden = true
            qhsp2.isHidden = true
            zdbz.isHidden = false
            kxbz.isHidden = false
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func getData() {
        getData1 { [weak self] in
            if self?.stype == 1 {
                self?.getData2(EWEUser.lgf.userId ?? "")
            } else if self?.stype == 2 {
                self?.getData2(EWEUser.lgf.userId ?? "")
            } else if self?.stype == 3 {
                self?.getData2(EWEUser.lgf.userId ?? "")
            } else if self?.stype == 4 {
                self?.getData2("")
            } else if self?.stype == 5 {
                self?.getData5(EWEUser.lgf.userId ?? "")
            }
//            self?.getData3()
            self?.getData4()
        }
    }
    
}

extension BzVC {
    @objc func s_back() {
        if self.stype == 4 || self.stype == 5 {
            self.navigationController?.popViewController(animated: false)
        } else {
            self.view.alpha = 0
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    // 添加对比医生
    @objc func s_add_dbys() {
        if self.bzModels.count == 0 {
            return
        }
        let arr: [String] = self.bzModels.map { (model) -> String in
            return model.operatorName
        }
        ysqhV?.removeFromSuperview()
        ysqhV = YsqhV()
        ysqhV.lgf_ViewName = "医生选择"
        ysqhV.showIn(self.view, 44, arr, s_dbys_i) { [weak self] (view, name, index) in
            self?.dbys_b.lgf_SubViewRemove()
            self?.s_dbys_i.removeAll()
            self?.selectCoordinates.removeAll()
            for (i, idx) in index.enumerated() {
                self?.s_dbys_i.append(idx)
                let model = self?.bzModels[idx]
                self?.selectCoordinates.append(model?.coordinate ?? [])
                let dbys = dbysV.init()
                dbys.bzModel = model
                dbys.tag = idx
                dbys.mz.text = model?.operatorName ?? ""
                dbys.layer.cornerRadius = 16
                dbys.layer.borderColor = UIColor.init(lgf_HexString: "8FC6F6")?.cgColor
                dbys.layer.borderWidth = 0.0
                dbys.ys.backgroundColor = model?.backgroundColor
                dbys.backgroundColor = UIColor.darkGray.withAlphaComponent(0.15)
                dbys.lgf_AddTap(target: self, action: #selector(self?.s_dbys(_:)))
                self?.dbys_b.addSubview(dbys)
                dbys.snp.makeConstraints { (make) in
                    if i == 0 {
                        make.left.equalTo(0)
                    } else {
                        make.left.equalTo(self!.dbys_b.subviews[self!.dbys_b.subviews.count - 2].snp.right).offset(5)
                    }
                    make.height.equalToSuperview().offset(-10)
                    make.centerY.equalToSuperview()
                }
            }
            self?.creatCoordinate(self?.selectCoordinates)
            self?.dbys_b.lgf_AutoContentSizeWidth(0)
        }
    }
    
    // 选中对比医生
    @objc func s_dbys(_ sender: UITapGestureRecognizer) {
        if let view = sender.view as? dbysV {
            self.dbys_b.subviews.forEach { (v) in
                if let sview = v as? dbysV {
                    sview.layer.borderWidth = 0.0
                }
            }
            if self.bzModel == nil || self.bzModel != view.bzModel {
                self.bzModel = view.bzModel
                view.layer.borderWidth = 3.0
                self.creatCoordinate([view.bzModel.coordinate])
            } else {
                self.bzModel = nil
                self.creatCoordinate(self.selectCoordinates)
            }
        }
    }
    
    // 评分
    @objc func s_pf(_ sender: UITapGestureRecognizer) {
        if self.bzModel == nil {
            SVProgressHUD.showError("请点击顶部栏选中需要评分的标注医生")
            return
        }
        PfV().showIn(self.view, self.bzModel.rating, self.bzModel.ratingRemark, self.type == 4 || self.auditStatus == 10) { [weak self] (pfv, name, data) in
            let pf = (data["pf"] as? Int) ?? 0
            let bz = (data["bz"] as? String) ?? ""
            let paramet: [String: Any] = [
                "ratingRemark": bz,
                "rating": pf.description
            ]
            self?.pfR(paramet, { [weak self] in
                self?.bzModel.rating = pf
                self?.bzModel.ratingRemark = bz
                self?.bzModels.forEach({ (model) in
                    if model.markId == self?.bzModel.markId {
                        model.rating = pf
                        model.ratingRemark = bz
                    }
                })
            })
        }
    }
    
    // 查看报告
    @objc func s_ckbg(_ sender: UITapGestureRecognizer) {
        if self.reportPath.count == 0 || self.reportPath == EWEUrl.File_URL {
            SVProgressHUD.showError("暂无心超报告")
            return
        }
        let vc = WebVC()
        vc.url = self.reportPath
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // 医生标注
    @objc func s_ysbz(_ sender: UITapGestureRecognizer) {
        let vc = BzVC()
        if stype == 2 {
            vc.stype = 4
        } else if stype == 3 {
            vc.stype = 5
        }
        if type == 3 {
            vc.auditStatus = 20
        } else if type == 4 {
            vc.auditStatus = 10
        }
        vc.type = 10
        vc.id = id
        self.navigationController?.pushViewController(vc, animated: false)
    }
    
    // 完成
    @objc func s_wc(_ sender: UITapGestureRecognizer) {
        if self.bzModel == nil {
            return
        }
        if type == 1 || type == 2 {
            BzV().showIn(self.view, "标注完成", self.zsjgArr, self.bzModel.diagnosis, type == 2, self.bzModel.remark) { [weak self] (bzv, name, ids, remark) in
                let alertVC = UIAlertController.init(title: nil, message: "确定要完成标注吗?", preferredStyle: .alert)
                alertVC.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { [weak self] (action) in
                    self?.wcbzPost(ids)
                }))
                alertVC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil))
                UIApplication.shared.keyWindow?.rootViewController?.present(alertVC, animated: true, completion: nil)
            }
        } else if type == 3 || type == 4 {
            BzV().showIn(self.view, "审核完成", self.zsjgArr, self.bzModel.diagnosis, type == 4, self.bzModel.remark) { [weak self] (bzv, name, ids, remark) in
                WcshV().showIn(self!.view) { [weak self] (wcshv, name, data) in
                    self?.wcshPost(ids, data)
                }
            }
        } else if type == 5 || type == 6 {
            BzV().showIn(self.view, "仲裁完成", self.zsjgArr, self.bzModel.diagnosis, type == 6, self.bzModel.remark) { [weak self] (bzv, name, ids, remark) in
                let alertVC = UIAlertController.init(title: nil, message: "确定要完成仲裁吗?", preferredStyle: .alert)
                alertVC.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { [weak self] (action) in
                    self?.wczcPost(ids)
                }))
                alertVC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil))
                UIApplication.shared.keyWindow?.rootViewController?.present(alertVC, animated: true, completion: nil)
            }
        }
    }
    
    // 作废
    @objc func s_zf(_ sender: UITapGestureRecognizer) {
        let alertVC = UIAlertController.init(title: nil, message: "确定要作废样本并退出吗？", preferredStyle: .alert)
        alertVC.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { [weak self] (action) in
            self?.ybzfDelete()
        }))
        alertVC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil))
        UIApplication.shared.keyWindow?.rootViewController?.present(alertVC, animated: true, completion: nil)
    }
    
    // 听诊模式
    @objc func s_tzms(_ sender: UITapGestureRecognizer) {
        if let label = sender.view as? UILabel {
            let picker = LGFRightPickerView()
            picker.lgf_ViewName = "听诊模式"
            let datas = ["无", "心音模式", "肺音模式", "混合音模式"]
            let sindex = datas.lgf_IndexOfObject(label.text?.lgf_RemoveBlank() ?? "无")
            picker.showIn(self.view, datas, sindex) { (view, name, index) in
                if index == 0 {
                    label.text = "   听诊模式"
                } else {
                    label.text = (index == 3 ? "  " : "   ") + datas[index]
                }
            }
        }
    }
    
    // 整段标注
    @objc func s_zdbz(_ sender: UITapGestureRecognizer) {
        if self.bzModel == nil {
            SVProgressHUD.showError("请点击顶部栏选中需要查看的标注医生")
            return
        }
        BzV().showIn(self.view, "整段标注", self.bznrArr, self.bzModel.markOption, type == 2 || type == 4 || type == 6, self.bzModel.remark) { [weak self] (bzv, name, ids, remark) in
            self?.zdBiaoZhu(ids, remark)
        }
    }
    
    // 切换 sp
    @objc func s_qhsp(_ sender: UITapGestureRecognizer) {
        if let label = sender.view as? UILabel {
            if label.text == "切换至SP" {
                label.text = "切换至PH"
                self.ph_l.isHidden = true
                self.ph_r.isHidden = true
                self.kxbz.isHidden = true
                self.ph_view_i.isHidden = true
                self.yz.isHidden = false
                self.sp_view.isHidden = false
                self.sp_l.isHidden = false
                if self.spNums.count == 0 {
                    self.getData3()
                }
            } else {
                label.text = "切换至SP"
                self.ph_l.isHidden = false
                self.ph_r.isHidden = false
                self.kxbz.isHidden = (type == 10) || (type == 1) || (type == 3) || (type == 5)
                self.ph_view_i.isHidden = false
                self.yz.isHidden = true
                self.sp_view.isHidden = true
                self.sp_l.isHidden = true
            }
        }
    }
    
    // 框选标注
    @objc func s_kxbz(_ sender: UITapGestureRecognizer) {
        if kxbz_l.text == "框选标注" {
            kxbz_l.text = "确认标注"
            if kxbzv == nil {
                let top = CGFloat(ph_view_i.lgf_Height / 2) - CGFloat(ph_view_i.lgf_Height / 4)
                let left = CGFloat(ph_view.lgf_Width / 2) - CGFloat(ph_view_i.lgf_Height / 4) + CGFloat(ph_view.contentOffset.x)
                let right = -CGFloat(ph_view_i.lgf_Width - ph_view.lgf_Width) - CGFloat(ph_view.lgf_Width / 2) + CGFloat(ph_view_i.lgf_Height / 4) + CGFloat(ph_view.contentOffset.x)
                let bottom = -(CGFloat(ph_view_i.lgf_Height / 2) - CGFloat(ph_view_i.lgf_Height / 4))
                kxbzv = KxBzV.init()
                kxbzv.addPanView()
                ph_view_i.addSubview(kxbzv)
                kxbzv.snp.makeConstraints { (make) in
                    make.top.equalTo(top)
                    make.left.equalTo(left)
                    make.right.equalTo(right)
                    make.bottom.equalTo(bottom)
                }
                kxbzv.callRect = { [weak self] (bz, rect, isEdit) in
                    if isEdit {
                        BzV().showIn((self?.view)!, "框选标注", self!.bznrArr, [], true, "") { (bzv, name, ids, remark) in
                            self?.kxBiaoZhu(ids, remark)
                        }
                    } else {
                        self?.kxbz_l.text = "框选标注"
                        self?.kxbzv.removeFromSuperview()
                        self?.kxbzv = nil
                    }
                }
            }
        } else {
            var isHave = false
            let xx: CGFloat = 2.0
            self.ph_view_i.subviews.forEach { (v) in
                if v != kxbzv {
                    let aa: Bool = CGFloat(kxbzv.lgf_X + xx) >= v.lgf_X
                    let bb: Bool = CGFloat(CGFloat(CGFloat(kxbzv.lgf_X - xx - v.lgf_X) + kxbzv.lgf_Width) - xx) <= v.lgf_Width
                    let cc: Bool = CGFloat(CGFloat(CGFloat(kxbzv.lgf_Y - xx - v.lgf_Y) + kxbzv.lgf_Height) - xx) <= v.lgf_Height
                    let dd: Bool = CGFloat(kxbzv.lgf_Y + xx) >= v.lgf_Y
                    let aaa: Bool = CGFloat(kxbzv.lgf_X - xx) < v.lgf_X
                    let bbb: Bool = CGFloat(CGFloat(CGFloat(kxbzv.lgf_X + xx - v.lgf_X) + kxbzv.lgf_Width) + xx) > v.lgf_Width
                    let ccc: Bool = CGFloat(CGFloat(CGFloat(kxbzv.lgf_Y + xx - v.lgf_Y) + kxbzv.lgf_Height) + xx) > v.lgf_Height
                    let ddd: Bool = CGFloat(kxbzv.lgf_Y - xx) < v.lgf_Y
                    if (aa && bb && cc && dd) || (aaa && bbb && ccc && ddd) {
                        isHave = true
                        return
                    }
                }
            }
            if isHave {
                SVProgressHUD.showError("当前标注与已标注内容重合")
                return
            }
            BzV().showIn(self.view, "框选标注", self.bznrArr, [], true, "") { [weak self] (bzv, name, ids, remark) in
                self?.kxBiaoZhu(ids, remark)
            }
        }
    }
    
    // 播速放大
    @objc func s_sd(_ sender: UITapGestureRecognizer) {
        let picker = LGFRightPickerView()
        picker.lgf_ViewName = "播放速率"
        let data = ["x0.5", "x0.75", "x1", "x1.5", "x2", "x3"]
        let sindex = data.lgf_IndexOfObject(self.sd_l.text ?? "x1")
        picker.showIn(self.view, data, sindex) { [weak self] (view, name, index) in
            self?.sd_l.text = data[index]
            let rate = data[index].replacingOccurrences(of: "x", with: "")
            self?.stop()
            self?.player.reset()
            self?.player.audioPlayer.rate = Float(rate) ?? 1.0
        }
    }
    
    // 声音放大
    @objc func s_sy(_ sender: UITapGestureRecognizer) {
        let picker = LGFRightPickerView()
        picker.lgf_ViewName = "声音放大"
        let data = ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x10", "x20", "x30", "x40"]
        let sindex = data.lgf_IndexOfObject(self.sy_l.text ?? "x1")
        picker.showIn(self.view, data, sindex) { [weak self] (view, name, index) in
            self?.sy_l.text = data[index]
            EWERequest.downloadFile("1", ["type": (index + 1).description, "path": (self?.wavPath ?? "").replacingOccurrences(of: EWEUrl.File_URL, with: "")], "wav") { (success) in
                self?.wavBdPath = success
                self?.stop()
                self?.player.reset()
            } _: { (error) in
                SVProgressHUD.showError("数据下载失败")
            }
        }
    }
    
    // x 轴放大
    @objc func s_xz(_ sender: UITapGestureRecognizer) {
        let picker = LGFRightPickerView()
        picker.lgf_ViewName = "X轴放大"
        let data = ["1x", "2x", "3x", "4x", "5x"]
        let sindex = data.lgf_IndexOfObject(self.xz_l.text ?? "1x")
        picker.showIn(self.view, data, sindex) { [weak self] (view, name, index) in
            self?.stop()
            self?.xz_l.text = data[index]
            self?.xf = index + 1
            let bs: Double = pow(2, Double(self!.xf))
            self?.ph_view_i_w = CGFloat(1920.0 * bs / 2.0)
            self?.ph_view.contentSize = CGSize.init(width: CGFloat(self!.ph_view_i_w), height: self!.ph_view.lgf_Height)
            self?.reloadLine { (i, sp) in
                sp.layer.setNeedsDisplay()
            }
            self?.sp_view.snp.updateConstraints { (make) in
                make.width.equalTo(self!.ph_view_i_w)
            }
            self?.ph_view_i.snp.updateConstraints { (make) in
                make.width.equalTo(self!.ph_view_i_w)
            }
            self?.ph_view_i_top.snp.updateConstraints { (make) in
                make.width.equalTo(self!.ph_view_i_w)
            }
            self?.ph_view_i_top.subviews.forEach { (v) in
                v.removeFromSuperview()
            }
            self?.reloadTZQ()
            if self?.bzModel == nil {
                self?.creatCoordinate(self!.selectCoordinates)
            } else {
                self?.creatCoordinate([self!.bzModel!.coordinate])
            }
            if self?.kxbzv != nil {
                self?.kxbzv.snp.removeConstraints()
                self?.kxbzv.snp.makeConstraints { (make) in
                    make.top.equalTo(CGFloat(self!.ph_view_i.lgf_Height / 2) - CGFloat(self!.ph_view_i.lgf_Height / 4))
                    make.left.equalTo(CGFloat(self!.ph_view.lgf_Width / 2) - CGFloat(self!.ph_view_i.lgf_Height / 4))
                    make.right.equalTo(-CGFloat(self!.ph_view_i_w - self!.ph_view.lgf_Width) - CGFloat(self!.ph_view.lgf_Width / 2) + CGFloat(self!.ph_view_i.lgf_Height / 4))
                    make.bottom.equalTo(-(CGFloat(self!.ph_view_i.lgf_Height / 2) - CGFloat(self!.ph_view_i.lgf_Height / 4)))
                }
                self?.ph_view_i.bringSubviewToFront(self!.kxbzv)
            }
        }
    }
    
    // y 轴放大
    @objc func s_yz(_ sender: UITapGestureRecognizer) {
        let picker = LGFRightPickerView()
        picker.lgf_ViewName = "Y轴放大"
        let data = ["1x", "2x", "3x", "5x", "10x"]
        let sindex = data.lgf_IndexOfObject(self.yz_l.text ?? "10x")
        picker.showIn(self.view, data, sindex) { [weak self] (view, name, index) in
            self?.yz_l.text = data[index]
            var num: Int = 10
            if index == 4 {
                num = 10
            } else if index == 3 {
                num = 5
            } else if index == 2 {
                num = 3
            } else if index == 1 {
                num = 2
            } else if index == 0 {
                num = 1
            }
  
            self?.reloadLine({ [weak self] (i, sp) in
                let l = (i * self!.spNums.count / 100)
                let r = ((i + 1) * self!.spNums.count / 100)
                let nums = Array(self!.spNums[l..<r])
                sp.show(nums, num)
            })
            
        }
    }
}

extension BzVC {
    
    func reloadLine(_ call: @escaping ((Int, LineBackView2) -> Void)) {
        var i = 0
        Timer.lgf_RunTimer(self, S: 0.01) { [weak self] (timer) in
            if let v = self?.sp_view.subviews[i] as? LineBackView2 {
                call(i, v)
            }
            i += 1
            if i == (self?.sp_view.subviews.count)! {
                timer?.lgf_StopTimer()
                return
            }
        }
    }
    
    // 刷新诊区
    func reloadTZQ() {
        let ph_view_i_w6: CGFloat = self.ph_view_i_w / 60000.0
        let begin1 = ph_view_i_w6 * CGFloat((self.areaFirst?["begin"] as? Int) ?? 0)
        let end1 = ph_view_i_w6 * CGFloat((self.areaFirst?["end"] as? Int) ?? 0)
        let tzq1 = UILabel.init()
        tzq1.text = "二尖瓣听诊区"
        tzq1.font = UIFont.systemFont(ofSize: 12)
        tzq1.textColor = UIColor.white
        tzq1.backgroundColor = UIColor.black
        tzq1.textAlignment = .center
        ph_view_i_top.addSubview(tzq1)
        tzq1.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(begin1)
            make.width.equalTo(end1 - begin1)
        }
        
        let begin2 = ph_view_i_w6 * CGFloat((self.areaSecond?["begin"] as? Int) ?? 0)
        let end2 = ph_view_i_w6 * CGFloat((self.areaSecond?["end"] as? Int) ?? 0)
        let tzq2 = UILabel.init()
        tzq2.text = "三尖瓣听诊区"
        tzq2.font = UIFont.systemFont(ofSize: 12)
        tzq2.textColor = UIColor.white
        tzq2.backgroundColor = UIColor.black
        tzq2.textAlignment = .center
        ph_view_i_top.addSubview(tzq2)
        tzq2.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(begin2)
            make.width.equalTo(end2 - begin2)
        }
        
        let begin3 = ph_view_i_w6 * CGFloat((self.areaThird?["begin"] as? Int) ?? 0)
        let end3 = ph_view_i_w6 * CGFloat((self.areaThird?["end"] as? Int) ?? 0)
        let tzq3 = UILabel.init()
        tzq3.text = "肺动脉瓣听诊区"
        tzq3.font = UIFont.systemFont(ofSize: 12)
        tzq3.textColor = UIColor.white
        tzq3.backgroundColor = UIColor.black
        tzq3.textAlignment = .center
        ph_view_i_top.addSubview(tzq3)
        tzq3.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(begin3)
            make.width.equalTo(end3 - begin3)
        }
        
        let begin4 = ph_view_i_w6 * CGFloat((self.areaFourth?["begin"] as? Int) ?? 0)
        let end4 = ph_view_i_w6 * CGFloat((self.areaFourth?["end"] as? Int) ?? 0)
        let tzq4 = UILabel.init()
        tzq4.text = "主动脉瓣听诊区"
        tzq4.font = UIFont.systemFont(ofSize: 12)
        tzq4.textColor = UIColor.white
        tzq4.backgroundColor = UIColor.black
        tzq4.textAlignment = .center
        ph_view_i_top.addSubview(tzq4)
        tzq4.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(begin4)
            make.width.equalTo(end4 - begin4)
        }
        
        let begin5 = ph_view_i_w6 * CGFloat((self.areaFifth?["begin"] as? Int) ?? 0)
        let end5 = ph_view_i_w6 * CGFloat((self.areaFifth?["end"] as? Int) ?? 0)
        let tzq5 = UILabel.init()
        tzq5.text = "主动脉瓣第二听诊区"
        tzq5.font = UIFont.systemFont(ofSize: 12)
        tzq5.textColor = UIColor.white
        tzq5.backgroundColor = UIColor.black
        tzq5.textAlignment = .center
        ph_view_i_top.addSubview(tzq5)
        tzq5.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(begin5)
            make.width.equalTo(end5 - begin5)
        }
    }

    // 刷新已标注
    func creatCoordinate(_ coordinates: [[[String: Any]]]?) {
        self.ph_view_i.subviews.forEach { (v) in
            if v.lgf_ViewName == "已标注" {
                v.removeFromSuperview()
            }
        }
        let ph_view_i_w6: CGFloat = self.ph_view_i_w / 60000.0
        let ph_view_i_h5: CGFloat = self.ph_view_i.lgf_Height
        coordinates?.forEach({ (coordinate) in
            coordinate.forEach { (data) in
                let smarkOption = (data["markOption"] as? [String]) ?? []
                let remark = (data["markRemark"] as? String) ?? ""
                let sid = (data["id"] as? String) ?? ""
                let backgroundColor = UIColor.init(lgf_HexString: (data["backgroundColor"] as? String) ?? "F0F0F0")
                let top: CGFloat = CGFloat((data["top"] as? CGFloat) ?? CGFloat((data["top"] as? Int) ?? 0))
                let height: CGFloat = CGFloat((data["height"] as? CGFloat) ?? CGFloat((data["height"] as? Int) ?? 0))
                let duration: [Any] = ((data["duration"] as? [Any]) ?? [0, 0])
                let left = ((duration.first as? CGFloat) ?? CGFloat((duration.first as? Int) ?? 0))
                let width = ((duration.last as? CGFloat) ?? CGFloat((duration.last as? Int) ?? 0)) - left
                let ybzv = KxBzV.init()
                ybzv.lgf_ViewName = "已标注"
                ybzv.lgf_Name = sid
                ybzv.canEdit = type == 2 || type == 4 || type == 6
                ybzv.bzColor = backgroundColor
                self.ph_view_i.addSubview(ybzv)
                ybzv.snp.makeConstraints { (make) in
                    make.top.equalTo(ph_view_i_h5 * top)
                    make.left.equalTo(ph_view_i_w6 * left)
                    make.width.equalTo(ph_view_i_w6 * width)
                    make.height.equalTo(ph_view_i_h5 * height)
                }
                ybzv.callRect = { [weak self] (bz, rect, isEdit) in
                    if isEdit {
                        BzV().showIn((self?.view)!, "框选标注", self!.bznrArr, smarkOption, false, remark) { (bzv, name, ids, remark) in
                            self?.kxBiaoZhu(ids, remark)
                        }
                    } else {
                        self?.bzModel.coordinate = self?.bzModel.coordinate.filter({ (dict) -> Bool in
                            let ssid = (dict["id"] as? String) ?? ""
                            return bz.lgf_Name != ssid
                        })
                        self?.kxBiaoZhuR {
                            SVProgressHUD.showSuccess("删除框选标注成功")
                        }
                    }
                }
            }
        })
    }
    
}

